﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Bzzb.Model;
using FreeSql;
using FreeSql.Internal.Model;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OfficeOpenXml;

namespace Bzzb.Controllers
{
    public class JiLuController : BaseController
    {
        private readonly IWebHostEnvironment _env;
        private readonly ILogger<JiLuController> _logger;
        private readonly IConfiguration _configuration;
        public JiLuController(ILogger<JiLuController> logger, IFreeSql fsql, IConfiguration configuration, IWebHostEnvironment env) : base(fsql)
        {
            this._env = env;
            this._logger = logger;
            this._configuration = configuration;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Index([FromForm] DateTime begintime, [FromForm] DateTime endtime, [FromForm] int doPage = 1, [FromForm] int pageNumber = 1, [FromForm] int pageSize = 10)
        {
            ISelect<JiLu> iselect = _fsql.Select<JiLu>().OrderBy("id desc");
            List<JiLu> jilus;
            long total = -1;
            if (doPage == 0)
            {
                jilus = await iselect.ToListAsync();
            }
            else
            {
                jilus = await iselect.Count(out total).Page(pageNumber, pageSize).ToListAsync();
            }
            JObject data = new();
            data.Add("total", total);
            data.Add("data", jilus == null ? null : JArray.FromObject(jilus));
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Save([FromForm] JiLu jilu)
        {
            long id = await _fsql.Insert(jilu).ExecuteIdentityAsync();
            return RenderJson(data: id);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Delete([FromForm] long id) {
            int affrows = await _fsql.Delete<JiLu>().Where(jl => jl.Id == id).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Show([FromForm] long id) {
            JiLu jilu = await _fsql.Select<JiLu>().Where(jl => jl.Id == id).ToOneAsync();
            return RenderJson(data: jilu);
        }
    }
}
